<template>
  <div>
    <div></div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleDelete"> 删除 </a-button>
        <a-button type="primary" @click="handleUpdate(null)"> 更新 </a-button>
        <a-button type="primary" @click="handleGiveUp"> 放弃 </a-button>
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:info-standard-line',
              tooltip: '查看',
              onClick: handleView.bind(null, record),
            },
            {
              icon: 'clarity:note-edit-line',
              tooltip: '修改',
              onClick: handleEdit.bind(null, record),
              ifShow: record.isAdmin,
            },
            {
              icon: 'ant-design:retweet-outlined',
              tooltip: '更新',
              onClick: handleUpdate.bind(null, record),
            },
            {
              icon: 'ant-design:rollback-outlined',
              tooltip: '恢复',
              onClick: handleRecover.bind(null, record),
              ifShow: record.status == '已删除',
            },
            {
              icon: 'ant-design:file-text-outlined',
              tooltip: '干预',
              onClick: handleIntervene.bind(null, record),
              ifShow: record.isAdmin,
            },
          ]"
        />
      </template>
    </BasicTable>
  </div>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, onMounted, h } from 'vue';

  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import {
    getFlowListRecord,
    getFlowDelBatch,
    getFlowDelToDustbin,
    getFlowDiscardBatch,
    getFlowRefreshFlow,
    getFlowRefreshFlowBatch,
    getFlowRecover,
  } from '/@/api/flowManage/flowManage';

  import { useTabs } from '/@/hooks/web/useTabs';
  import { useRoute, useRouter } from 'vue-router';
  import { cloneDeep } from 'lodash-es';
  import { useGo } from '/@/hooks/web/usePage';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();

  import { columns, searchFormSchema } from './flowRecord.data';

  export default defineComponent({
    // eslint-disable-next-line vue/component-definition-name-casing
    name: 'flowRecord',
    components: { BasicTable, TableAction },
    setup() {
      const { createMessage, createConfirm } = useMessage();
      const searchInfo = ref({
        op: 'search',
        typeCode: '',
      });
      const { setTitle } = useTabs();
      const route = useRoute();
      const query = ref<any>({
        tabName: '',
        typeCode: '',
      });
      const fetch = () => {
        if (route.query) {
          query.value = cloneDeep(route.query);
          if (unref(query).tabName) {
            setTitle(unref(query).tabName);
            setProps({ title: unref(query).tabName });
          }
          if (unref(query).typeCode) {
            searchInfo.value.typeCode = unref(query).typeCode;
            setProps({ searchInfo: unref(searchInfo) });
          }
        }
      };
      onMounted(fetch);

      const [registerTable, { reload, setProps, getSelectRowKeys, setSelectedRowKeys, getForm }] =
        useTable({
          title: '记录',
          api: getFlowListRecord,
          columns,
          formConfig: {
            labelWidth: 80,
            schemas: searchFormSchema,
            autoSubmitOnEnter: true,
          },
          searchInfo: {
            op: 'search',
          }, //额外的参数

          beforeFetch: (info) => {
            let newInfo = info;
            if (newInfo.dates && newInfo.dates.length > 0) {
              newInfo.fromDate = newInfo.dates[0];
              newInfo.toDate = newInfo.dates[1];
              delete newInfo.dates;
            }
            return newInfo;
          },
          useSearchForm: true,
          showTableSetting: true,
          bordered: true,
          indexColumnProps: { width: 50 },
          showIndexColumn: true,
          rowKey: 'id',
          rowSelection: {
            type: 'checkbox',
          },
          actionColumn: {
            width: 200,
            title: '操作',
            dataIndex: 'action',
            slots: { customRender: 'action' },
            fixed: 'right',
          },
        });

      const go = useGo();

      const { currentRoute } = useRouter();
      function handleEdit(record: Recordable) {
        let tabTitle = record['tabTitle'] ? record['tabTitle'] : currentRoute.value.meta.title;

        go({
          path: '/smartModuleAddEditView',
          query: {
            isTab: true,
            isUpdate: 2,
            parentPath: unref(currentRoute).path,
            moduleCode: unref(query).formCode || record.moduleCode, //listPage.value.moduleCode,
            id: record['fdaoId'],
            formCode: unref(query).formCode, //listPage.value.formCode,
            treeNodeCode: '',
            isTreeView: false,
            titleName: `编辑-${tabTitle}`,
            cacheName: `smartModuleAddEditViewEdit${record.id}`,
          },
        });
      }

      //查看
      function handleView(record: Recordable) {
        go({
          path: '/processShow',
          query: {
            flowId: record['id'],
            title: record['title'],
            isFromProcess: true,
            cacheName: `processShow${record['id']}`,
            recordType: 2, //从流程记录查看
          },
        });
      }
      //干预
      const handleIntervene = (record) => {
        go({
          path: '/processShow',
          query: {
            flowId: record['id'],
            title: record['title'],
            isFromProcess: true,
            cacheName: `processShow${record['id']}`,
            recordType: 3, //从流程记录查看直接显示到干预
          },
        });
      };
      //更新
      const handleUpdate = (record) => {
        let params: { ids?: string; flowId?: string } = {};
        let req: (data) => Promise<void>;
        if (!record) {
          const selectRowKeys = getSelectRowKeys();
          if (selectRowKeys.length == 0) {
            return createMessage.warning('请选择数据');
          }
          params.ids = selectRowKeys.join(',');
          req = getFlowRefreshFlowBatch;
        } else {
          params.flowId = record.id;
          req = getFlowRefreshFlow;
        }
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.prompt')),
          content: () => h('span', '您确定要更新么'),
          onOk: async () => {
            try {
              await req(params);
              createMessage.success('操作成功');
              handleSuccess();
            } catch (err) {
              console.error(err);
            } finally {
            }
          },
        });
      };

      //更新
      const handleRecover = (record) => {
        let params: { flowId?: string } = {};
        params.flowId = record.id;
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.prompt')),
          content: () => h('span', '您确定要恢复么'),
          onOk: async () => {
            try {
              await getFlowRecover(params);
              createMessage.success('操作成功');
              handleSuccess();
            } catch (err) {
              console.error(err);
            }
          },
        });
      };

      async function handleDelete() {
        const { getFieldsValue } = getForm();
        const model = getFieldsValue();
        const selectRowKeys = getSelectRowKeys();
        if (selectRowKeys.length == 0) {
          return createMessage.warning('请选择数据');
        }
        let req: (data) => Promise<void>;
        if (model['status'] == '-11') {
          req = getFlowDelBatch;
        } else {
          req = getFlowDelToDustbin;
        }
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.prompt')),
          content: () => h('span', '您确定要删除么'),
          onOk: async () => {
            try {
              const params = {
                ids: selectRowKeys.join(','),
              };
              await req(params);
              createMessage.success('操作成功');
              handleSuccess();
            } catch (err) {
              console.error(err);
            } finally {
            }
          },
        });
      }

      function handleSuccess() {
        setSelectedRowKeys([]);
        reload();
      }

      //放弃
      const handleGiveUp = () => {
        const selectRowKeys = getSelectRowKeys();
        if (selectRowKeys.length == 0) {
          return createMessage.warning('请选择数据');
        }
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.prompt')),
          content: () => h('span', '您确定要放弃么'),
          onOk: async () => {
            try {
              const params = {
                ids: selectRowKeys.join(','),
              };
              await getFlowDiscardBatch(params);
              createMessage.success('操作成功');
              handleSuccess();
            } catch (err) {
              console.error(err);
            } finally {
            }
          },
        });
      };

      return {
        registerTable,
        handleEdit,
        handleUpdate,
        handleView,
        handleIntervene,
        handleDelete,
        handleSuccess,
        handleGiveUp,
        handleRecover,
      };
    },
  });
</script>
